<template>
    <a-drawer
        :visible="visible"
        title="AI批量写标题"
        :width="700"
        @close="closeClick"
    >
        <a-form layout="vertical">
            <a-form-item label="标题描述" v-bind="validateInfos.content">
                <a-textarea v-model:value="modelRef.content" placeholder="简单描述标题内容" />
            </a-form-item>
            <a-form-item>
                <template #label>
                    <a-row :gutter="[16,16]">
                        <a-col>
                            标题中包含关键词
                        </a-col>
                        <a-col class="dec">
                            同时添加多个关键词，请用 "回车键隔开"
                        </a-col>
                    </a-row>
                </template>
                <a-select
                    v-model:value="modelRef.keywords"
                    mode="tags"
                    style="width: 100%"
                    placeholder="请输入关键词名称"
                    :showSearch="false"
                    :open="false"
                ></a-select>
            </a-form-item>
            <a-form-item label="标题字数">
                <a-input-number    v-model:value="modelRef.words_num" :min="1" :controls="false" :max="props.wordsNum">
                    <template #addonAfter>
                        <div @click="addNum('words_num')" class="nput-number">
                             +
                        </div>
                    </template>
                    <template #addonBefore>
                        <div @click="minusNum('words_num')" class="nput-number">
                            -
                        </div>
                    </template>
                </a-input-number>
            </a-form-item>
            <div style="font-weight: 600;">生成设置</div>
            <a-row style="width: 100%;margin-top: 10px;" :gutter="[16,16]">
                <a-col :span="12">
                    <a-form-item label="标题风格">
                        <a-select
                            v-model:value="modelRef.words_style"
                            style="width: 100%"
                            placeholder="示例: 正常"
                            :options="titleStyleOptions"
                        ></a-select>
                    </a-form-item>
                </a-col>
                <a-col :span="12">
                    <a-form-item label="语言">
                        <a-select
                            v-model:value="modelRef.language"
                            style="width: 100%"
                        >
                        <a-select-option value="chinese">中文</a-select-option>
                        <a-select-option value="english">英文</a-select-option>
                    </a-select>
                    </a-form-item>
                </a-col>
                <a-col :span="12">
                    <a-form-item :label="props.type ? '生成标题数': '生成标题数组'" style="margin-bottom: 6px" >
                        <a-input-number v-model:value="modelRef.number" :min="1" @change="numberChange" @blur="(val)=> blurChange(val)" :controls="false">
                            <template #addonAfter>
                                <div @click="addNum" class="nput-number">
                                    +
                                </div>
                            </template>
                            <template #addonBefore>
                                <div @click="minusNum" class="nput-number">
                                    -
                                </div>
                            </template>
                        </a-input-number>
                    </a-form-item>
                    <div :style="{display: isNumber? 'block':'none'}" :class="isNumber ?'dec-text' :''">生成数量必须在1到20之间</div>
                </a-col>
                <a-col :span="12" v-if="!props.type">
                    <a-form-item label="每个标题组生成的文本数" style="margin-bottom: 6px" >
                        <a-input-number v-model:value="textNumber" :min="1"  @change="numTextberChange" @blur="(val)=> blurTextChange(val)" :controls="false">
                            <template #addonAfter>
                                <div @click="addTextNum" class="nput-number">
                                    +
                                </div>
                            </template>
                            <template #addonBefore>
                                <div @click="minusTextNum" class="nput-number">
                                    -
                                </div>
                            </template>
                        </a-input-number>
                    </a-form-item>
                </a-col>
            </a-row>
        </a-form>
        <template #footer>
            <a-row justify="end" :gutter="[16,16]">
                <a-col>
                    <a-button @click="closeClick">取消</a-button>
                </a-col>
                <a-col>
                    <a-button type="primary" @click="submitClick" :loading="loading">确定</a-button>
                </a-col>
            </a-row>
        </template>
    </a-drawer>
</template>

<script setup>
import { ref, onMounted, computed,reactive,createVNode,watch} from "vue";
import request from "@/common/utils/request";
import { Form,Modal } from 'ant-design-vue';
import { baseText_config } from "../../../shotstack/MixedCutPlatforms/utools/index";
const useForm = Form.useForm;
import { ExclamationCircleOutlined } from '@ant-design/icons-vue';

const props = defineProps({
    visible: {
        type: Boolean,
        default:false
    },
    wordsNum:{
        type: [String,Number],
        default: 500,
    },
    number:{
        type: [String,Number],
        default: 20,
    },
    type:{
        type: String,
        default: '',
    },
    titleListNum:{
        type: [String,Number],
        default: 0,
    }
});

const emits = defineEmits(["submit","close"]);

const loading=ref(false)

const titleStyleOptions=ref([
    {
        value: '正常',
        label: '正常',
    },
    {
        value: '包含有紧迫感和惊喜感的标点符号',
        label: '包含有紧迫感和惊喜感的标点符号',
    },
    {
        value: '具有挑战性和悬念的表述',
        label: '具有挑战性和悬念的表述',
    },
    {
        value: '描述具体体验',
        label: '描述具体体验',
    },
    {
        value: '使用emoji表情增加活力',
        label: '使用emoji表情增加活力',
    },
    {
        value: '以口语化表述',
        label: '以口语化表述',
    },
    {
        value: '通过正面刺激、负面刺激吸引用户眼球',
        label: '通过正面刺激、负面刺激吸引用户眼球',
    }
])

const modelRef = reactive({
    content: '',
    keywords:[],
    words_num:1,
    words_style:'正常',
    language:'chinese',
    number:1,
});

      
const textNumber =ref(1)

const rulesRef = reactive({
    content: [{
        required: true,
        message: '请输入标题描述',
    }],
});

const {
    resetFields,
    validate,
    validateInfos,
} = useForm(modelRef, rulesRef);

const addNum=(key)=>{
    if(key == 'words_num'){
        if(modelRef.words_num >= props.wordsNum){
            modelRef.words_num = 500
            return
        }
        modelRef.words_num++
    }else{
        if(props.number >0 && modelRef.number >= props.number){
            modelRef.number = 20
            return
        }
        modelRef.number ++
    }
  
}
const minusNum=(key)=>{
    if(key == 'words_num'){
        if(modelRef.words_num<=1){
            return
        }
        modelRef.words_num--
    }else{
        if(modelRef.number<=1){
            return
        }
        modelRef.number--
    }

}


const addTextNum=()=>{
    if(textNumber.value >=5){
        textNumber.value = 5
        return
    }
    textNumber.value ++
}
const minusTextNum=()=>{
    if(textNumber.value<=1){
            return
    }
    textNumber.value--
}

const blurTextChange=()=>{
    if(textNumber.value>=5){
        textNumber.value = 5
    }
}

const closeClick=()=>{
    resetFields()
    emits('close')
}

const titleArr=ref([])

const submitClick=()=>{
 
    if(modelRef.number<=0){
        modelRef.number = 1
    }

    validate().then(() => {
        if(props.titleListNum>0){
            Modal.confirm({
                title: '提示',
                icon: createVNode(ExclamationCircleOutlined),
                content:'确定要覆盖有生成好的标题组吗?',
                onOk() {
                    successSubmit()
                },
                onCancel() {},
                okText:'确定',
                cancelText:'取消'
            });
         return
        }
        successSubmit()
    })
}

const isNumber = ref(0)
const numberChange=(e)=>{
    if(props.number>0){
        if(e>20){
            isNumber.value = 1
            modelRef.number = 20
        }else{
            isNumber.value = 0
        }
    }
}

const blurChange=(e)=>{
    if(props.number>0){
        if(e.target.value<=20){
            isNumber.value = 0
        }
    }
}

const successSubmit=()=>{
    loading.value = true
    titleArr.value =[]
    if(!props.type){
        // 循环 modelRef.number 次，生成对应数量的标题组
        for (let i = 0; i < modelRef.number; i++) {
                const titleGroup = {
                    label: "标题组",
                    id: titleArr.value.length + 1,
                    task_id: null,
                    isselected: false,
                    data: []
                };
                titleArr.value.push(titleGroup);
        }

        // 循环 textNumber 次，为每个标题组添加数据
        for (let j = 0; j < textNumber.value; j++) {
            request.post('/work_ai', '/user/ai/toTitle', modelRef).then((res) => {
                let timer = setInterval(() => {
                    request.get('/work_ai', '/user/ai/toTitle/result', { task_id: res.result.task_id }).then((result) => {
                        console.log(result.result,'result.result')
                        if (result.result.status == 'done') {
                            clearInterval(timer);
                            result.result.data.forEach((item, index) => {
                                if (index < modelRef.number) {
                                    const text_config_data = baseText_config();
                                    text_config_data.text = item.title;
                                    titleArr.value[index].data.push(text_config_data);
                                    titleArr.value[index].task_id = res.result.task_id;
                                }
                            });

                            // 检查是否所有标题组都已经生成了足够的数据
                            const allDataGenerated = titleArr.value.every(group => group.data.length === textNumber.value);
                        console.log(allDataGenerated,'allDataGenerated')

                            if (allDataGenerated) {
                                loading.value = false;
                                emits('submit',titleArr.value)
                                resetFields()
                            }
                        }
                    });
                }, 1000);
            });
        }
    }else{
        request.post('/work_ai', '/user/ai/toTitle', modelRef).then((res) => {
            let timer = setInterval(() => {
                request.get('/work_ai','/user/ai/toTitle/result',{task_id:res.result.task_id}).then((result)=>{
                    if(result.result.status=='done'){
                        clearInterval(timer)
                        if(Number(props.type)){
                            loading.value = false;
                            emits('submit',result.result.data,modelRef.keywords)
                            resetFields()
                        }
                    }
                })
            }, 1000);
        });
    }

}

watch(
    ()=>props.visible,
    (val)=>{
        if(val){
            if(!Number(props.type)){
                modelRef.words_num  = 10
            }
        }else{
            textNumber.value = 1
        }
    }
)


</script>

<style lang="less" scoped>
.dec{
    font-size: 12px;
    top: 2px;
    color: #9f9d9d;

}

:deep(input:not([type='range'])){
    text-align: center;
}
:deep(.ss-input-number-group-addon:first-child){
    cursor: pointer;
}
:deep(.ss-input-number-group-addon:last-child){
    cursor: pointer;
}
.nput-number{
    width: 100%;
    height: 100%;
    padding: 0 11px
}
.dec-text{
    color: red;
}
</style>